import os

import cv2
import numpy as np

from abnormal_width_statistics import get_video_name_set
from option import parse_args


def videos_mean(args, func, template: str, mask_lower_threshold=0., mask_upper_threshold=0.):
    diffs = os.path.join(args.root_dir, 'diffs')
    video_name_set = get_video_name_set(args)
    for video_name_pair in video_name_set:
        mean_min, mean_max = 255., 0.
        video_path = os.path.join(diffs, video_name_pair[2])
        count_less_equal_than = 0
        count_more_equal_than = 0
        for diff in os.listdir(video_path):
            mask = cv2.imread(os.path.join(video_path, diff), cv2.IMREAD_GRAYSCALE)
            mean_min = min(mean_min, np.mean(mask))
            mean_max = max(mean_max, np.mean(mask))
            if np.mean(mask) <= mask_lower_threshold:
                count_less_equal_than += 1
            if np.mean(mask) >= mask_upper_threshold:
                count_more_equal_than += 1
        # sub = mean_max - mean_min
        if (mean_min <= mask_lower_threshold or mean_max >= mask_upper_threshold) and count_less_equal_than < 10:
            func(template.format(video_name_pair[0], video_name_pair[1], video_name_pair[2], mean_min, mean_max,
                                 count_less_equal_than, count_more_equal_than))


def main():
    args = parse_args()
    print(args)
    args.save = False
    if args.save:
        with open('abnormal_mean_statistics.dat', 'w') as f:
            videos_mean(args, f.write, '{},{},{},{:.2f},{:.2f},{},{}\n', mask_lower_threshold=10.,
                        mask_upper_threshold=50.)
    else:
        videos_mean(args, print, '{},{},{},{:.2f},{:.2f},{},{}', mask_lower_threshold=10., mask_upper_threshold=50.)


if __name__ == '__main__':
    main()
